package cc.yugu.yhdw.webserver.web.controller.security.basic;

import cc.yugu.yhdw.common.annotation.ViewModel;
import cc.yugu.yhdw.common.constant.ConstEnum;
import cc.yugu.yhdw.common.domain.basic.Agent;
import cc.yugu.yhdw.common.domain.basic.AgentInOutMoney;
import cc.yugu.yhdw.common.domain.basic.Area;
import cc.yugu.yhdw.common.domain.basic.User;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.json.PageResult;
import cc.yugu.yhdw.webserver.constant.AppConstEnum;
import cc.yugu.yhdw.webserver.entity.SessionUser;
import cc.yugu.yhdw.webserver.service.basic.AgentInOutMoneyService;
import cc.yugu.yhdw.webserver.service.basic.AgentService;
import cc.yugu.yhdw.webserver.service.basic.AreaService;
import cc.yugu.yhdw.webserver.web.controller.security.SecurityController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 运营商控制器
 *
 * @Date:Created in 2018/7/17 10:24
 * @Author:
 * @Modified By: zjn 2018/7/17 10:24
 */
@Controller
@RequestMapping(value = "/security/basic/agent")
public class AgentController extends SecurityController {

    @Autowired
    AgentService agentService;
    @Autowired
    AgentInOutMoneyService agentInOutMoneyService;
    // 新增
    @Autowired
    AreaService areaService;

    // 该注解用于将Controller的方法返回的对象，通过适当的HttpMessageConverter转换为指定格式后，写入到Response对象的body数据区，
    // 使用时机：返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；
    @ResponseBody
    @ViewModel(ViewModel.JSON_ARRAY)
    @RequestMapping(value = "tree.htm")
    public void tree(String dummy, Integer agentId, Integer showAgency, HttpServletResponse response) throws Exception {
        response.setContentType(ConstEnum.ContentType.JSON.getValue());
        agentService.tree(dummy, agentId, showAgency != null && showAgency == 1, response.getOutputStream());
    }

    @RequestMapping(value = "index.htm")
    public void index(Model model) {
        model.addAttribute(MENU_CODE_NAME, AppConstEnum.Menu.MENU_01_01.getValue());
    }
    /**
    * 分页查询运营商信息
    *
    * @Param: [search, request]
    * @Return: cc.yugu.yhdw.common.entity.json.PageResult
    * @Author By: zjn 2018/7/17  10:25
    */
    @RequestMapping("page.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public PageResult page(Agent search, HttpServletRequest request) {
//        if (getSessionUser(request).getType()== User.Type.AGENCY.getValue()||getSessionUser(request).getType()== User.Type.SUPPLIER.getValue()){
//            return null;
//        }
        //if (search.getParentId() == null) {
            if (getSessionUser(request).getType() == User.Type.AGENT.getValue()) {
                search.setId(getSessionUser(request).getAgentId());
//                search.setParentId(getSessionUser(request).getAgentId());
            }
        //}
        // else if (search.getParentId() == 0) {
            // 代理商登录不显示
            if (getSessionUser(request).getType() == User.Type.AGENCY.getValue()) {
                search.setId(-1);
            }
        //}
        return PageResult.successResult(agentService.findPage(search));
    }
    /**
    * 返回值为void类型，返回到add.ftl 页面，，在前台新建运营商信息
    * 
    * @Param: []
    * @Return: void
    * @Author By: zjn 2018/7/17  10:49
    */ 
    @RequestMapping(value = "add.htm")
    public void add() {
    }
    /**
    * 保存运营商信息，前台获取
    *
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/17  10:26
    */
    @RequestMapping(value = "edit.htm")
    public String edit(Model model, int id) {
        Agent entity = agentService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/basic/agent/edit";
    }
    /**
    * 前台新建运营商信息，插入数据
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/17  10:36
    */ 
    @RequestMapping("create.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult create(Agent entity) {
        return agentService.insert(entity);
    }
    /**
    * 前台更新后，更新数据库
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/17  10:37
    */ 
    @RequestMapping("update.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult update(Agent entity) {
        return agentService.update(entity);
    }
    /**
    * 删除
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/17  10:37
    */ 
    @RequestMapping("delete.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult delete(int id) {
        return agentService.delete(id);
    }
    /**
    * 是否启用
    * 
    * @Param: [id, activeFlag]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/17  10:37
    */ 
    @RequestMapping("disable.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult disable(int id,int activeFlag) {
        return agentService.disable(id,activeFlag);
    }
    /**
    * 查看（包括左栏 基本信息、资金明细、下栏的关闭）
    * 
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/17  10:38
    */ 
    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping(value = "view.htm")
    public String view(Model model, int id) {
        Agent entity = agentService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("id", id);
        }
        return "/security/basic/agent/view";
    }
    /**
    * 查看  基本信息（统计换电收入、套餐收入（押金收入统计目前没有做））
    * 
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/17  11:27
    */ 
    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping(value = "view_basic_info.htm")
    public String viewBasicInfo(Model model, Integer id) {
        Agent entity = agentService.find(id);

        Double sumMoney1=0.0;
        Double sumMoney2=0.0;
        // 查询运营商流水表中的按次换电总收入
        List<AgentInOutMoney> agentInOutMoneyHuan =agentInOutMoneyService.find(entity.getId(),AgentInOutMoney.BizType.CHARGE_INCOME.getValue());
        if (agentInOutMoneyHuan == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        }
        // 遍历总收入
        for(AgentInOutMoney huan : agentInOutMoneyHuan){
            // 转成double型
            Double money1 = huan.getMoney()!=null?Double.parseDouble(huan.getMoney().toString()):0.0;
            // 累计求和
            sumMoney1+=money1;
        }
        model.addAttribute("sumMoney1",sumMoney1);
        // 查询运营商流水表中的套餐总收入
        List<AgentInOutMoney> agentInOutMoneyTaoCan = agentInOutMoneyService.find(entity.getId(),AgentInOutMoney.BizType.PACKET_INCOME.getValue());
        if (agentInOutMoneyTaoCan == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        }
        for(AgentInOutMoney taocan : agentInOutMoneyTaoCan){
            Double money2 = taocan.getMoney()!=null?Double.parseDouble(taocan.getMoney().toString()):0.0;
            // 套餐求和
            sumMoney2+=money2;
        }
        model.addAttribute("sumMoney2",sumMoney2);
        // 运营商详细地址
        String pName = areaService.find(entity.getProvinceId());
        String cName = areaService.find(entity.getCityId());
        String dName = areaService.find(entity.getDistrictId());
        if(pName!=null&&cName!=null&dName!=null){
            String pcdName = pName + "-" + cName + "-" + dName;
            model.addAttribute("pcdName",pcdName);
        }

        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/basic/agent/view_basic_info";
    }
    /**
    * 查看 资金明细
    * 
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/17  11:28
    */ 
    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping(value = "view_in_out_money.htm")
    public String viewInOutMoney(Model model, int id) {
        Agent entity = agentService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("id", id);
        }
        return "/security/basic/agent/view_in_out_money";
    }

}
